// Copyright (c) 2021-2023, Arm Limited and Contributors. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

#include <array>

#include "Driver_USART.h"

static const uint32_t baud_rate = 115200;

extern ARM_DRIVER_USART Driver_USART0;
extern ARM_DRIVER_USART Driver_USART1;

static ARM_DRIVER_USART *init_uart(size_t i)
{
    static ARM_DRIVER_USART *devices[] = {&Driver_USART0, &Driver_USART1};

    if (i >= sizeof(devices)) {
        return NULL;
    }

    if ((devices[i]->Initialize(NULL) != ARM_DRIVER_OK) || (devices[i]->PowerControl(ARM_POWER_FULL) != ARM_DRIVER_OK)
        || (devices[i]->Control(ARM_USART_MODE_ASYNCHRONOUS, baud_rate) != ARM_DRIVER_OK)) {
        return NULL;
    }
    /* Some drivers have TX and RX enabled by default and lacks option to enable/disable them. */
    int ret = devices[i]->Control(ARM_USART_CONTROL_TX, 1);
    if (ret != ARM_DRIVER_OK && ret != ARM_DRIVER_ERROR_UNSUPPORTED) {
        return NULL;
    }
    ret = devices[i]->Control(ARM_USART_CONTROL_RX, 1);
    if (ret != ARM_DRIVER_OK && ret != ARM_DRIVER_ERROR_UNSUPPORTED) {
        return NULL;
    }

    return devices[i];
}

void serial_setup(std::array<ARM_DRIVER_USART *, 2> &serials)
{
    for (size_t i = 0; i < serials.size(); i++) {
        serials[i] = init_uart(i);
    }
}
